package cn.wolfcode.crm.web.controller;

import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IPermissionService;
import cn.wolfcode.crm.service.IRoleService;
import cn.wolfcode.crm.util.JsonResult;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IPermissionService permissionService;

    // 提供一个方法处理查询所有部门数据请求，响应 HTML
    @RequestMapping("/list")
    @RequiresPermissions(value = {"role:list","角色列表"},logical = Logical.OR)
    public String list(Model model, @ModelAttribute("qo") QueryObject qo) {
        //调用service的方法的到结果集
        PageInfo result = roleService.query(qo);
        //共享结果集：在页面遍历显示
        model.addAttribute("result", result);
        return "role/list"; //返回视图名称：加上前缀和后缀的jsp
    }

    @RequestMapping("/input")
    @RequiresPermissions(value = {"role:input","角色编辑"},logical = Logical.OR)
    public String input(Long id, Model model) {

        if (id != null) { // 点击了修改按钮过来
            Role role = roleService.get(id);
            model.addAttribute("role", role);
        }
        //查询所有的权限并共享
        model.addAttribute("permissions", permissionService.listAll());
        //查询全部角色，然后共享
        model.addAttribute("roles", roleService.listAll());
        return "role/input"; // /WEB-INF/views/role/input.ftl
    }


    @RequestMapping("/saveOrUpdate")
    @RequiresPermissions(value = {"role:saveOrUpdate","角色编辑或保存"},logical = Logical.OR)
    public String saveOrUpdate(Role role, Long[] ids) {
        if (role.getId() == null) { // 代表新增
            roleService.save(role, ids);
        } else { // 代表修改
            roleService.update(role, ids);
        }
        return "redirect:/role/list.do";  // http://localhost/role/list.do
    }


    @RequestMapping("/delete")
    @RequiresPermissions(value = {"role:delete","角色删除"},logical = Logical.OR)
    @ResponseBody
    public JsonResult delete(Long id) {
        roleService.delete(id);
        return new JsonResult();
    }
}
